function collect(obj) {
  let ret = obj
  if (obj.children) {
    for (const o of obj.children) {
      ret = [...ret, ...collect(o)]
    }
  }
  return ret
}

export function useFieldFindByValue(arr, field, value) {
  if (arr == null) return null
  for (const obj of arr) {
    if (obj[field] === value) {
      return collect(obj)
    }
    const ret = find(obj.children, field, value)
    if (ret) return ret
  }
  return null
}


// 创建toolTip
export function createToolTip(el, row, value) {
  const { id } = row
  const tooltipDom = document.createElement('div')
  tooltipDom.style.cssText = `
        display: inline-block;
        max-width: 400px;
        max-height: 400px;
        position: absolute;
        top: ${el.clientY + 5}px;
        left: ${el.clientX}px;
        padding:5px 10px;
        overflow: auto;
        font-size: 12px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #595959;
        background: #fff;
        border-radius: 3px;
        z-index: 19999;
        box-shadow: 0 4px 12px 1px #ccc;
      `
  tooltipDom.innerHTML = value
  tooltipDom.setAttribute('id', `tooltip-${id}`)
  // 将浮层插入到body中
  document.body.appendChild(tooltipDom)
}


// 删除tooltip
export function removeToolTip(row) {
  const { id } = row
  const tooltipDomLeave = document.querySelectorAll(`#tooltip-${id}`)
  if (tooltipDomLeave.length) {
    tooltipDomLeave.forEach(dom => {
      document.body.removeChild(dom)
    })
  }
}


// 对象中的属性值必须全都不为空
export function objValueNotEmpty(params) {
  return Object.values(params).every(o => {
    return typeof o !== 'undefined' && o !== null && o !== ''
  })
}


// 图片转base64
export function imgURLToBase64(url) {
  return new Promise((resolve, reject) => {
    let canvas = document.createElement('canvas')
    const context = canvas.getContext('2d')
    const img = new Image() // 通过构造函数绘制图片实例
    img.crossOrigin = 'Anonymous' // 处理图片跨域问题，服务器也需允许跨域
    img.src = url
    img.onload = function() {
      // 该加载过程为异步事件，请先确保获取完整图片
      canvas.width = img.width
      canvas.height = img.height
      if (context) {
        context.drawImage(img, 0, 0) // 将图片绘制在canvas中
      }
      const URLData = canvas.toDataURL('image/png')
      resolve(URLData)
      canvas = null
    }
    img.onerror = function() {
      reject(new Error('图片加载失败'))
    }
  })
}


export function useTrim(value) {
  if (value) value = value.replace(/^\s*|\s*$/g, '')
  if (!value) return ''
  else return value
}


export function useDownloadFile(url = '', fileName = '下载的文件') {
  fetch(url)
    .then(res => res.blob())
    .then(blob => {
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = fileName
      document.body.appendChild(link)
      link.click()
      window.URL.revokeObjectURL(link.href)
      document.body.removeChild(link)
    })
}